package resolver

import resolver.analyzer.Analyzer
import resolver.analyzer.SimpleTextAnalyzer
import resolver.query.BatchedQuery
import resolver.query.Query
import resolver.query.SynonymQuery
import types.Hit
import resolver.query.InchiKeyQuery
import resolver.query.InchiQuery
import resolver.query.CasQuery
import resolver.query.HMDBQuery
import resolver.query.KeggQuery
import resolver.query.LipidMapQuery

/**
 * uses the queryClass table for compound lookups
 * User: wohlgemuth
 * Date: Feb 2, 2010
 * Time: 3:27:47 PM
 *
 */
class DatabaseContentResolver extends AbstractResolver {

  private static DatabaseContentResolver instance = null;

  //all registered queries which can be run
  private Set<Query> registeredQueries = new HashSet<Query>()

  /**
   * private datbaase content resolver
   */
  private DatabaseContentResolver() {

    registeredQueries.add(new SynonymQuery())
    registeredQueries.add(new InchiQuery())
    registeredQueries.add(new InchiKeyQuery())
    registeredQueries.add(new CasQuery())
    registeredQueries.add(new KeggQuery())
    registeredQueries.add(new HMDBQuery())
    registeredQueries.add(new LipidMapQuery())


    this.setBatchEnabledByDefault true
  }

  /**
   * get an instance of the resolver
   * @return
   */
  static DatabaseContentResolver getInstance(Analyzer
                                             analyzer = new SimpleTextAnalyzer()) {
    if (instance == null) {
      instance = new DatabaseContentResolver()
      instance.setAnalyzer analyzer
    }
    return instance
  }

  protected Set<Hit> doBatchResolve(Set<String> set) {
    Set<Hit> res = new HashSet<Hit>()

    //go over all queries
    registeredQueries.each {Query query ->
      //go over all results
      if (query instanceof BatchedQuery) {
        logger.debug "query is batchable..."
        BatchedQuery bquery = query

        set.each {String q ->
          bquery.addQuery q
        }

        logger.debug "executing batched query"
        res.addAll(bquery.executeQuery())

      }
      else {
        logger.debug "query is not batchable, so executed in default mode..."

        set.each {String value ->
          query.executeQuery(value).each {Hit hit ->

            //add the result to the result set
            res.add(hit)

          }
        }
      }
    }
    return res
  }
}